package com.android.clinic.app.ui.main.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.clinic.app.R;
import com.android.clinic.app.entity.DepartmentInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.ui.doctor.DepartmentClassifyActivity;
import com.android.clinic.app.ui.widget.GridViewWrapper;
import com.android.clinic.app.ui.widget.GroupChooseView;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.LocalDataUtils;
import com.android.clinic.app.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cheng on 2018/1/26.
 */
public class ClassifyView extends LinearLayout {

    private Context mContext;
    private ViewPager mViewPager;
    private LinearLayout layIndex;
    private GroupChooseView mGroupChooseView;
    private List<GridViewAdapter> adapterList = new ArrayList<>();
    private List<GridView> mGridViews = new ArrayList<>();
    public ArrayList<DepartmentInfo> classifyInfoList = new ArrayList<>();
    private Map<Integer, Map<Integer, ImageView>> imageMaps = new LinkedHashMap<>();

    private int currentPage;
    private int pageNo = 0;
    public static int pageSize = 8; // 每页显示数量
    private int columns = 2;
    private List<Map> dataList = new ArrayList<>();

    private OnTouchListener onTouchViewListener;

    public ClassifyView(Context context) {
        super(context);
        mContext = context;
    }

    public ClassifyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ClassifyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void initUI(Context context, int pageSize, int columns) {
        mContext = context;
        this.pageSize = pageSize;
        this.columns = columns;

        int padding = DisplayUtil.dip2px(10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.getScreenWidth(),
                (Utils.getScreenWidth() / columns) * 2 + padding);
        layIndex = (LinearLayout) findViewById(R.id.layout_index);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mViewPager.setOffscreenPageLimit(0);
        mViewPager.setPadding(0, padding, 0, 0);
        mViewPager.setLayoutParams(params);
    }

    public void initData(int position) {
        if (classifyInfoList.size() == 0) {
            new ParesDataThread(position).start();
        }
    }

    private class ParesDataThread extends Thread {

        int position = 0;

        private ParesDataThread(int position) {
            this.position = position;
        }

        @Override
        public void run() {
            // 获取数据
            classifyInfoList = (ArrayList<DepartmentInfo>) LocalDataUtils.objectMap.get(position);
            handler.sendEmptyMessage(0);
        }
    }

    private Handler handler = new Handler() {

        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != classifyInfoList && classifyInfoList.size() > 0) {
                int labelSize = classifyInfoList.size();
                dataList.clear();
                for (int i = 0; i < labelSize ; i++) {
                    Map map = new HashMap();
                    map.put("id", classifyInfoList.get(i).getId());
                    map.put("image", classifyInfoList.get(i).getImg());
                    map.put("name", classifyInfoList.get(i).getName());
                    map.put("status", classifyInfoList.get(i).getStatus());
                    dataList.add(map);
                }
                // 计算页数
                int listSize = dataList.size();
                if (listSize % pageSize != 0) {
                    pageNo = (listSize / pageSize) + 1;
                } else {
                    pageNo = (listSize / pageSize);
                }
                mGridViews.clear();
                adapterList.clear();
            }

            for (int j = 0; j < pageNo; j++) {
                Map<Integer, ImageView> map = new LinkedHashMap<>();
                GridViewWrapper appPage = new GridViewWrapper(mContext);
                appPage.setSelector(new ColorDrawable(Color.TRANSPARENT));
                GridViewAdapter adapter = new GridViewAdapter(mContext, dataList, j);
                adapterList.add(adapter);
                appPage.setAdapter(adapter);
                appPage.setNumColumns(columns);
                appPage.setOnItemClickListener(listener);
                mGridViews.add(appPage);
                imageMaps.put(j, map);
            }

            if (pageNo > 1) {
                layIndex.removeAllViews();
                mGroupChooseView = new GroupChooseView(mContext, layIndex, GroupChooseView.TYPE_IMAGE);
                mGroupChooseView.setCount(mGridViews.size());
                mGroupChooseView.setImageResource(R.drawable.icon_page_on, R.drawable.icon_page_off);
                mGroupChooseView.initView();
            } else {
                layIndex.setVisibility(View.GONE);
            }

            ClassifyPagerAdapter pagerAdapter = new ClassifyPagerAdapter();
            mViewPager.setAdapter(pagerAdapter);
            mViewPager.setCurrentItem(0);
            mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    currentPage = position;
                    mGroupChooseView.selectedViewIndex(currentPage);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

            if (null != onTouchViewListener) {
                mViewPager.setOnTouchListener(onTouchViewListener);
            }
        }
    };


    private class GridViewAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        private List<Map> mList = new ArrayList<>();

        public List<Map> getList() {
            return mList;
        }

        private GridViewAdapter(Context context, List<Map> list, int page) {
            inflater = LayoutInflater.from(context);
            int i = page * pageSize;
            int end = i + pageSize;
            while ((i < list.size()) && (i < end)) {
                mList.add(list.get(i));
                i++;
            }
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_home_grid_classify, null);
                holder = new ViewHolder();
                holder.ivPic = (ImageView) convertView.findViewById(R.id.iv_pic);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                holder.layItem = (LinearLayout) convertView.findViewById(R.id.layout_item);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        (Utils.getScreenWidth() / columns), (Utils.getScreenWidth() /columns));
                holder.layItem.setLayoutParams(params);
                if (onTouchViewListener != null) {
                    holder.ivPic.setOnTouchListener(onTouchViewListener);
                    holder.tvName.setOnTouchListener(onTouchViewListener);
                    holder.layItem.setOnTouchListener(onTouchViewListener);
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Map classifyInfo = mList.get(position);
            if (null != classifyInfo) {
                holder.tvName.setText(classifyInfo.get("name").toString());
                imageMaps.get(currentPage).put(position, holder.ivPic);
                ImageLoaderUtils.getInstance().loadNormalHomeImage(classifyInfo.get("image").toString(), holder.ivPic);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView ivPic;
            TextView tvName;
            LinearLayout layItem;
        }
    }

    private class ClassifyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mGridViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
          return view == (object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mGridViews.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mGridViews.get(position), 0);
            return mGridViews.get(position);
        }
    }

    /**
     * gridView点击事件
     */
    public AdapterView.OnItemClickListener listener = (parent, view, position, id) -> {
        if (!Utils.isFastClick()) {
            GridViewAdapter adapter = adapterList.get(currentPage);
            String labelName = adapter.getList().get(position).get("name").toString();
            String departId = adapter.getList().get(position).get("id").toString();

            Intent intent = new Intent(mContext, DepartmentClassifyActivity.class);
            intent.putExtra("classifyList", classifyInfoList);
            intent.putExtra("labelName", labelName);
            intent.putExtra("departId", departId);
            mContext.startActivity(intent);
        }
    };

    public void updateClassify() {
        if (adapterList.size() > 0) {
            GridViewAdapter adapter = adapterList.get(currentPage);
            if (null != adapter) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void recyclerClassify() {
        for (Integer page : imageMaps.keySet()) {
            Map<Integer, ImageView> maps = imageMaps.get(page);
            for (Integer key : maps.keySet()) {
                ImageView iv = maps.get(key);
                iv.setImageBitmap(null);
            }
        }
    }

}
